import axios from "axios";
import querystring from "querystring";

export function get(url) {
    // var url = '/api/3/stories/latest'
    axios({
        url: url,
        method: 'get'
    }).then(res => {
        console.log('--------get----------')
        console.log(res.data)
    })
}



export function get() {
    var url = '/api/3/stories/latest'
    axios({
        url: url,
        method: 'get'
    }).then(res => {
        console.log('--------get----------')
        console.log(res.data)
    })
}

export function post() {
    var url = '/newarchive/api/seedarchive/sys/appLogin'
    axios({
        url: url,
        method: 'post',
        headers: {
            'Content-type': 'application/json; charset=UTF-8'
        },
        //传json字符串
        //必须安装npm install --save querystring
        //这个就是一个body体
        // data:querystring.stringify({
        //     "password":'hmjtest',
        //     'username':'Hmjtest@888'
        // })
        data: {
            "password": 'hmjtest',
            'username': 'Hmjtest@888'
        }
    }).then(res => {
        console.log('--------post----------')
        console.log(res.data)
    })
}

//快捷方式
export function getKj() {
    var url = '/api/3/stories/latest'
    axios.get(url).then(res => {
        console.log('--------getKj----------')
        console.log(res.data)
    })
}

export function postKj() {
    var url = '/newarchive/api/seedarchive/sys/appLogin'
    axios.post(url, {
        "password": 'hmjtest',
        'username': 'Hmjtest@888'
    }, {
        headers: {
            'Content-type': 'application/json; charset=UTF-8'
        }
    }).then(res => {
        console.log('--------postKj----------')
        console.log(res.data)
    })
}


const instance = axios.create({
    //公共配置
    baseURL: 'http://localhost:8080',
    timeout: 1000,//超时时间
    headers: {'X-Custom-Header': 'foobar'}
});

/**
 * 请求前拦截器(客户触发按钮请求后)
 */
instance.interceptors.request.use(
    function (config) {
        //如果是post请求，则将数据转换成querystring
        //  if (config.method=='post'){
        //      config.data=querystring.stringify(config.data)
        //  }
        //成功,config包含着网络所有信息
        return config;
    }, function (error) {
        //失败,把错误信息返回出去
        return Promise.reject(error);
    });
/**
 * 响应前拦截器
 */
instance.interceptors.response.use(
    function (response) {
        //成功,可以判断是否200啥的,做业务护理后在把自定义的数据返回出去
        // 比如解析完response后suuccess(code,data,msg)
        return response;
    }, function (error) {
        //失败,把错误信息返回出去
        // return Promise.reject(error);
        //把数据返回出去
        errorHandler(error.response.status,error.response.info)
    });
var errorHandler = (status,info)=>{
   switch (status) {
     case 400:
         console.log('请求错误')
           break;
     case 401:
         console.log('未授权访问')
         break;
     case 403:
         console.log('禁止访问')
         break;
     case 404:
         console.log('请求地址出错')
         break;
   }
}

export default instance